#!/usr/bin/python
# -*- coding: utf-8 -*-
import tornado.ioloop
import tornado.web
import os
import importlib
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

_urls = None


def _init():
    """ 初始化
    """
    global _urls
    _urls = {}


def set_value(key, value):
    """ 定义一个全局变量 """
    _urls[key] = value


def get_value(key, defValue=None):
    """ 获得一个全局变量,不存在则返回默认值
    """
    try:
        return _urls[key]
    except KeyError:
        return defValue


def import_urls(rootDir):
    """ 动态导入各个服务的路由URL信息，并合并
    """
    list_dirs = os.walk(rootDir)
    for dirName, subdirList, fileList in list_dirs:
        for f in fileList:
            file_name = f
            if file_name == "urls.py":
                impPath = ""
                # print rootDir, dirName, sys.path[0]
                dir = dirName.replace(sys.path[0], "")
                if dir[-1:] != "/":
                    impPath = dir.replace("/", ".")[1:]
                else:
                    impPath = dir.replace("/", ".")[1:-1]
                # print impPath
                lib_path = impPath + "." + file_name[0:-3]
                print lib_path
                try:
                    mo = importlib.import_module(lib_path)
                    print mo
                    extend(mo.get_urls())
                except Exception as e:
                    print e.message
                    pass


def extend(urls):
    """ 扩展路由URL信息
    """
    all_urls = get_value("urls")
    all_urls.extend(urls)
    set_value("urls", all_urls)

if __name__ == "__main__":

    _init()
    set_value("urls", [])
    path = os.path.abspath(".")
    if(path[-3:] == "app"):  # 启动目录为/opt/fy/app
        import_urls(path+"/service")
        deploy_path = os.path.abspath("../deploy")
        import_urls(deploy_path)

    else:  # 启动目录为/opt/fy
        import_urls(path+"/app/service")
        deploy_path = os.path.abspath("deploy")
        import_urls(deploy_path)
        pass

    handler_urls = get_value("urls")

    application = tornado.web.Application(
        handlers=handler_urls,
    )

    server_port = 8868
    application.listen(server_port)
    tornado.ioloop.IOLoop.instance().start()
